﻿/// <reference path="KingsSharp.Config.js" />
/// <reference path="jquery-2.1.3-vsdoc.js" />
(function () {
    K = KingsSharp = window.KingsSharp = function () {

    };
    //程序初始化
    $(document).ready(function () {
        $(".p-icon-date").click(function () {
            WdatePicker({ dateFmt: 'yyyy-MM-dd' });
        });
        $(".p-icon-date-long").click(function () {
            WdatePicker({ dateFmt: 'yyyy-MM-dd HH:mm:ss' });
        });
        $(".p-icon-reload").click(function () {
            location.reload();
        });
        $(".ktabs li").each(function (i) {
            $(this).click(function () {
                $(".ktabs li").removeClass("selected");
                $(this).addClass("selected");
                $(".ktabs-details").children().hide();
                $(".ktabs-details").children().eq(i).show();
            });
        });
        if (typeof (layer)!="undefined")
        {
            KingsSharp.layer = layer;
            KingsSharp.layer.iframe = function (parameter, fuc) {
                var p={
                    title:"无标题文档",
                    type: 2,
                    area: ["480px","340px"],
                    fix: false, 
                    maxmin: true,
                    content: "",
                    btn: ["确定", "返回"],
                    callback: fuc,
                    initfull:false
                };
                $.extend(p, parameter);
                if (p.initfull)
                {
                    p.area = ["100%", "100%"];
                }
                var index = KingsSharp.layer.open(p);
                return index;
            };
            KingsSharp.layer.html = function (parameter, fuc) {
                var p = {
                    title: "无标题文档",
                    type: 1,
                    area: ["350px", "250px"],
                    fix: false,
                    maxmin: true,
                    content: "",
                    initfull: false,
                    shift:false
                };
                $.extend(p, parameter);
                var index = KingsSharp.layer.open(p);
                return index;
            };
        }
        if (typeof (SaveData) != "undefined" && parent.layer) {
            var index = parent.layer.getFrameIndex(window.name);
            parent.layer.regist(index, SaveData);
        }
        if($("#td-grid").size()>0)
        {
            var height = $("body").height();
            var formheight = $(".content-table").height();
            $("#td-grid").css("height", (height - formheight + 10) + "px");
        }
    });
    KingsSharp.BindForm = function (id, data) {
        var elerange = $("#" + id);
        function bind(e,val)
        {
            e.each(function () {
                var tagname = $(this)[0].tagName;
                if(tagname.toLowerCase()=="input" || tagname.toLowerCase()=="select" || tagname.toLowerCase()=="textarea")
                {
                    $(this).val(String(val));
                }
                else
                {
                    $(this).text(String(val));
                }
            })
        }
        for(var key in data)
        {
            var ele = elerange.find("[name='" + key + "']");
            if(typeof (data[key])!="object")
            {
                bind(ele, data[key]);
            }
        }
    };
    //注册地区选择器
   
    KingsSharp.PickeInit = function (id,values) {
        var province = $("#" + id).find("[data-picke='1']");
        var city = $("#" + id).find("[data-picke='2']");
        var borough = $("#" + id).find("[data-picke='3']");
      
        if (province.size() > 0)
        {
            var picker = new Picker();
            var provinceData = picker.getData(1);
            province.append("<option></option>");
            for(var i=0;i<provinceData.length;i++)
            {
                province.append("<option value=\"" + provinceData[i].i + "\">" + provinceData[i].n + "</option>");
            }
        }

        if (values != null && values!="")
        {
            var val = values.split(',');
            if (val.length > 0)
            {
                province.val(val[0]);
            }
            if (val.length > 1)
            {
                var code = province.val();
                if (city.size() > 0) {
                    city.html("<option></option>");
                    var picker = new Picker();
                    var citydata = picker.getData(2, code);
                    for (var j = 0; j < citydata.length; j++) {
                        city.append("<option value=\"" + citydata[j].i + "\">" + citydata[j].n + "</option>");
                    }
                    city.val(val[1]);
                }
            }
            if(val.length>2)
            {
                var code = city.val();
                if (borough.size() > 0) {
                    borough.html("<option></option>");
                    var picker = new Picker();
                    var boroughdata = picker.getData(3, code);
                    for (var j = 0; j < boroughdata.length; j++) {
                        borough.append("<option value=\"" + boroughdata[j].i + "\">" + boroughdata[j].n + "</option>");
                    }
                    borough.val(val[2]);
                }
            }
        }
        province.change(function () {
            var code = $(this).val();
            if (city.size() > 0) {
                city.html("<option></option>");
                if (borough)
                {
                    borough.html("<option></option>");
                }
                var picker = new Picker();
                var citydata=picker.getData(2,code);
                for(var j=0;j<citydata.length;j++)
                {
                    city.append("<option value=\"" + citydata[j].i + "\">" + citydata[j].n + "</option>");
                }
            }
        });
        if (city.size() > 0)
        {
            city.change(function () {
                var code = $(this).val();
                if(borough.size()>0)
                {
                    borough.html("<option></option>");
                    var picker = new Picker();
                    var boroughdata = picker.getData(3, code);
                    for (var j = 0; j < boroughdata.length; j++) {
                        borough.append("<option value=\"" + boroughdata[j].i + "\">" + boroughdata[j].n + "</option>");
                    }
                }
            });
        }
    };
    
    //验证
    KingsSharp.Validate = function () {
        if ($validate().begin()) {
            return true;
        }
        else {
            return false;
        }
    };
    //表单转Json
    KingsSharp.Form2Json = function () {
        return form2Json();
    };
    //深度赋值
    KingsSharp.ObjtoObj = function (NewObject, OldObject) {
        function clonePrototype() { }
        clonePrototype.prototype = NewObject;
        var obj = new clonePrototype();
        for (var ele in obj) {
            if (typeof (obj[ele]) == "object")
                KingsSharp.ObjtoObj(obj[ele], OldObject[ele]);
            else
                OldObject[ele] = obj[ele];
        }
    };
    //TreeGrid
    KingsSharp.GetTreeGrid = function () {

    };
    //Grid列表
    KingsSharp.GetGridData = function (gridid, parameter) {
        var myview = $.extend({}, $.fn.datagrid.defaults.view, {
            onAfterRender: function (target) {
                $.fn.datagrid.defaults.view.onAfterRender.call(this, target);
                var opts = $(target).datagrid('options');
                var vc = $(target).datagrid('getPanel').children('div.datagrid-view');
                vc.children('div.datagrid-empty').remove();
                if (!$(target).datagrid('getRows').length) {
                    var d = $('<div class="datagrid-empty"></div>').html(opts.emptyMsg).appendTo(vc);
                    d.css({
                        position: 'absolute',
                        left: 0,
                        top: 50,
                        width: '100%',
                        textAlign: 'center'
                    });
                }
            }
        });
        var LoadSuccess = function (dat) {

        };
        var loadError = function (error) {
            KingsSharp.Alert("加载远程数据发生错误");
        };
        var loadFilter = function (data) {
            if (data.Total != undefined) {
                data.total = data.Total;
                delete data.Total;
            }
            if (data.Rows != undefined) {
                data.rows = data.Rows;
                delete data.Rows;
            }
            return data;
        };
        var beforeLoad = function (param) {
            if (param.page) {
                param.pageIndex = param.page;
                delete param.page;
            }
            if (param.rows) {
                param.pageSize = param.rows;
                delete param.rows;
            }
            if (param.sort) {
                param.sortField = param.sort;
                delete param.sort;
            }
            if (param.order) {
                param.sortOrder = param.order;
                delete param.order;
            }
            param.where = getFilterGroup(param.filterRules);
        };
        function getFilterGroup(filterRules) {
            var group = KingsSharp.GetGridFilter != null ? KingsSharp.GetGridFilter() : "";
            return JSON.stringify(group);
        };
        var rownumbers = true, singleSelect = false, ctrlSelect = true, multiSort = false, pageSize = 30, toolbarData = [];

        var defaultparameter = {
            title: "",
            fit: true,
            columns: null,
            fitColumns: false,
            toolbar: "#toolpannel",
            url: "",
            loadMsg: "正在拼命加载，请稍候",
            rownumbers: rownumbers,
            singleSelect: singleSelect,
            ctrlSelect: ctrlSelect,
            multiSort: multiSort,
            pagination: true,
            pageNumber: 1,
            emptyMsg: "暂无数据",
            striped: true,
            nowrap: false,
            pageSize: pageSize,
            pageList: [1, 10, 30, 50, 100, 200],
            onBeforeLoad: beforeLoad,
            loadFilter: loadFilter,
            onLoadError: loadError,
            view: myview
        };
        $.extend(defaultparameter, parameter);
        var grid = $(gridid).datagrid(defaultparameter);
        var filter = KingsSharp.GridFilterInit != null ? new KingsSharp.GridFilterInit(".datagrid-filter-pannel") : null;
        return { Grid: grid, Filter: filter };
    };
    KingsSharp.Show = function (message, parameter) {
        if (layer)
        {
            var p = {
                type: 1,
                area: ["250px", "180px"],
                shade: false,
                time: 2500,
                shift: 2,
                offset: "rb",
                content: "\<\div style=\"padding:15px;\">" + message + "<\/div>"
            };
            $.extend(p, parameter);
            layer.open(p);
        }
        else if ($.messager && $.messager.show) {
            $.messager.show({
                title: '提示:',
                msg: message,
                timeout: 2500,
                showType: 'slide'
            });
        }
        else {
            alert(message);
        }
    };
    KingsSharp.Confirm = function (message, callback) {
        if (layer)
        {
            layer.confirm(message, { title: "提示", icon: 3 }, function (index) {
                layer.close(index);
                callback();
            });
        }
       else if ($.messager && $.messager.confirm) {
            $.messager.confirm("提示", message, function (r) {
                if (r && callback)
                {
                    callback();
                }
            });
        }
        else {
            if(confirm(message) && callback)
            {
                callback();
            }
        }
    };
    KingsSharp.Alert = function (message, type) {
        if (layer) {
            layer.alert(message, { icon: type == null ? 0 : type });
        }
        else if ($.messager && $.messager.alert) {
            $.messager.alert("提示:", message, type == null ? "warning" : type.toLocaleLowerCase());
        }
        else {
            alert(message);
        }
    };
    KingsSharp.ShowOrAlert = function (result,parameter) {
        if (result.Type.toLocaleLowerCase() == "error") {
            KingsSharp.Alert(result.Content, result.Type);
            return false;
        }
        else {
            KingsSharp.Show(result.Content, parameter);
            return true;
        }
    }
    KingsSharp.ConvertJSONDateToJSDateObject = function (jsondate) {
        var date = new Date(parseInt(jsondate.replace("/Date(", "").replace(")/", ""), 10));
        return date;
    };
    KingsSharp.JsonToData = function (jsondate, short) {
        if (jsondate == null) {
            return "";
        }
        var date = this.ConvertJSONDateToJSDateObject(jsondate);
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var day = date.getDate();
        var hours = date.getHours()
        var minutes = date.getMinutes();
        var seconds = date.getSeconds();
        month = month < 10 ? "0" + month.toString() : month;
        day = day < 10 ? "0" + day.toString() : day;
        hours = hours < 10 ? "0" + hours.toString() : hours;
        minutes = minutes < 10 ? "0" + minutes.toString() : minutes;
        seconds = seconds < 10 ? "0" + seconds.toString() : seconds;
        if (short) {
            return year + "-" + month + "-" + day;
        }
        else {
            return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
        }
    };
    //生成GUID
    KingsSharp.Guid = function (i) {
        function G() {
            return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
        }
        var rguid = "";
        if (i) {
            for (var s = 0; s < i; s++) {
                var guid = (G() + G() + "-" + G() + "-" + G() + "-" + G() + "-" + G() + G() + G()).toUpperCase();
                if (rguid != "") {
                    rguid += ",";
                }
                rguid += guid;
            }
        }
        else {
            rguid = (G() + G() + "-" + G() + "-" + G() + "-" + G() + "-" + G() + G() + G()).toUpperCase();
        }
        return rguid;
    };
    KingsSharp.Animation = function (type, min, max) {
        min = min || 0;
        max = max || 11;
        if (min > 11) { min = 11; }
        if (max > 11) { max = 11; }
        if (min > max) {
            console.warn("范围起值" + min + "大于止值" + max + ",自动将止值设为起值");
            max = min;
        }
        var animationIN = ["a-fadein", "a-fadeinB", "a-fadeinT", "a-fadeinL", "a-fadeinR"
            , "a-rotatein", "a-rotateinLB", "a-rotateinLT", "a-rotateinLT", "a-rotateinLT", "a-rotateinRB", "a-rotateinRT"
            , "a-flipinX", "a-flipinY"];
        var animationOUT = ["a-fadeout", "a-fadeoutB", "a-fadeoutT", "a-fadeoutL", "a-fadeoutR"
            , "a-rotateout", "a-rotateoutLB", "a-rotateoutLT", "a-rotateoutLT", "a-rotateoutLT", "a-rotateoutRB", "a-rotateoutRT"
            , "a-flipoutX", "a-flipoutY"];
        var i = KingsSharp.Random(min, max);
        return "";
        if (type == "in") {
            return animationIN[i];
        }
        else {
            return animationOUT[i];
        }
    };
    //生成随机数
    KingsSharp.Random = function (min, max) {
        if (!min) { min = 1; } if (!max) { max = 100 };
        return Math.floor(min + Math.random() * (max - min));
    };
    //将汉字转换为拼音 需引用py.js
    KingsSharp.Pinyin = function (value) {
        return ConvertPinyin(value);
    };
    //jquery Ajax异步请求 返回json数据
    KingsSharp.AjaxJson = function (url, parameter, call, msg) {
        var index = -1;
        msg = msg || "请求中...";
        if (KingsSharp.layer!=undefined)
        {
            index = K.layer.msg(msg, { icon: 16, shade: 0.2, time: false });
        }
        $.ajax({
            url: url,
            type: "post",
            data: parameter,
            dataType: "json",
            async: true,
            cache: false,
            success: function (data) {
                if(index!=-1)
                {
                    K.layer.close(index);
                }
                call(data);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                if (index != -1) {
                    K.layer.close(index);
                }
                KingsSharp.Alert("操作时发生错误，错误代码：" + XMLHttpRequest.status);
            }
        });
    };
    //查询类
    KingsSharp.filter = {
        rule: function (field, value, operate) {
            this.Field = field;
            this.Value = value;
            this.Operate = operate || "equal";
        },
        group: function () {
            this.Rules = [];
            this.Operate = "and";
            this.Group = [];
        }
    };
    KingsSharp.OnlyNum = function (e) {
        var event = e || window.event;
        if (!(event.keyCode == 46) && !(event.keyCode == 8)) {
            if (!((event.keyCode >= 48 && event.keyCode <= 57))) {
                event.returnValue = false;
            }
        }
    };
    KingsSharp.GetColor = function (objElement, callBack) {
        var obj;
        if (typeof (objElement) == "object") {
            obj = $(objElement);
        }
        else {
            obj = $("#") + objElement;
        }
        obj.spectrum({
            color: "#94A6C6",
            preferredFormat: "hex",
            showInput: true,
            change: function (color) {
                callBack(color.toHexString());
            }
        });
    };
    KingsSharp.StopEvent = function (e) {
        if (e.stopPropagation) { e.stopPropagation(); }
        else if (window.event) { window.event.cancelBubble = true; }
    };
    KingsSharp.IncludeStyle = function (url) {
        var link = document.createElement("link");
        link.rel = "stylesheet";
        link.type = "text/css";
        link.href = url;
        document.getElementsByTagName("head")[0].appendChild(link);
    };
    KingsSharp.IncludeJs = function (url) {
        var oScript = document.createElement("script");
        oScript.type = "text/javascript";
        oScript.src = url;
        document.getElementsByTagName("head")[0].appendChild(oScript);
    };
    //根据身份证号自动计算身份信息
    KingsSharp.GetIdNumberUserInfo = function (obj) {
        var userInfo = { Birthday: "", Age: 0, Sex: "" };
        var UUserCard = "";
        if (typeof (obj) == "object")
        {
            UUserCard = obj.value;
        }
        else
        {
            UUserCard = obj;
        }
        if (UUserCard.length != 18)
        {
            return null;
        }
        userInfo.Birthday = UUserCard.substring(6, 10) + "-" + UUserCard.substring(10, 12) + "-" + UUserCard.substring(12, 14);
        if (parseInt(UUserCard.substr(16, 1)) % 2 == 1) {
            userInfo.Sex = "男";
        } else {
            userInfo.Sex = "女";
        }
        var myDate = new Date();
        var month = myDate.getMonth() + 1;
        var day = myDate.getDate();
        var age = myDate.getFullYear() - UUserCard.substring(6, 10) - 1;
        if (UUserCard.substring(10, 12) < month || UUserCard.substring(10, 12) == month && UUserCard.substring(12, 14) <= day) {
            age++;
        }
        userInfo.Age = age;
        return userInfo;
    };
})();

(function ($) {
    $.fn.serializeJson = function () {
        var serializeObj = {};
        $(this.serializeArray()).each(function () {
            serializeObj[this.name] = this.value;
        });
        return serializeObj;
    };
})(jQuery);